// socketHandlers.js

const handleSocketEvents = (io, db) => {
  const userSockets = {};
  io.on("connection", (socket) => {
    let currentRoomId = null;

    socket.on("login", (data) => {
      // 将用户ID与Socket关联起来
      userSockets[data] = socket;
 
    });
    socket.on("joinRoom", (roomId) => {
      // 如果已经加入了聊天室，则先离开-----重要要不会串台
      if (currentRoomId) {
        socket.leave(currentRoomId);
      }
      // 加入新的聊天室
      socket.join(roomId);
      socket.broadcast.to(roomId).emit("joinRoom", roomId);
      currentRoomId = roomId;
      
    });

    socket.on("leaveRoom", (roomId) => {
      socket.leave(roomId);
      socket.broadcast.to(roomId).emit("leaveRoom", roomId);
    });

    socket.on("chatMessage", (data) => {
      const messageInfo = {
        user_id: data.user_id,
        room_id: data.room_id,
        username: data.username,
        message: data.message,
        avatar: data.avatar,
        moment: new Date(),
      };

    
      const sql = `INSERT INTO message SET ?`;
      db.query(sql, messageInfo, (err, results) => {
        if (err) {
     
          return;
        }
        if (results.affectedRows === 1) {
        
          socket.broadcast
            .to(data.room_id)
            .emit("chatMessage", messageInfo, data.room_id);
         
        }
      });
    });

    socket.on("deleteRoom", (roomId, roomName) => {
      socket.leave(roomId);
      socket.broadcast.to(roomId).emit("deleteRoom", `群聊(${roomName})已解散！`);
    });

    socket.on("deleteUser", (username, roomId) => {
      const userSocket = userSockets[username];

 
      if (userSocket) {
        userSocket.emit("deleteUser");
      }
      socket.broadcast.to(roomId).emit("delUser", roomId);
    });
  });
};

module.exports = handleSocketEvents;
